﻿import 'package:get/get.dart';
import 'event_summary_state.dart';
import 'event_summary_view.dart';
import '../../../../core/repository/default_api.dart';
import 'package:azring/services/ring_service.dart';

/// 事件小计控制器
class EventSummaryLogic extends GetxController {
  final EventSummaryState state = EventSummaryState();
  RingService get ringService => Get.find<RingService>();
  @override
  void onInit() {
    super.onInit();
    _loadEvents();
  }

  /// 加载事件数据
  Future<void> _loadEvents() async {
    try {
      state.isLoading.value = true;

      // 根据选中的时间段传递不同的参数
      // 0: 日, 1: 周, 2: 月
      final timeType = state.selectedPeriod.value;

      final dynamic apiData =
          await DefaultApi().queryEventSubtotalListGet<dynamic>(
        type: timeType.toString(),
        deviceSn: ringService.getCurrentDeviceSn(),
        isShowLoading: false,
      );

      if (apiData != null && apiData['data'] != null) {
        final data = apiData['data'];

        // 更新日期范围
        final dateStart = data['dateStart'] ?? '';
        final dateEnd = data['dateEnd'] ?? '';
        if (dateStart != 'null，null' && dateEnd != 'null，null') {
          state.dateRangeText.value = '$dateStart—$dateEnd';
        } else {
          _updateDateRangeText();
        }

        // 解析事件数据
        final eventDayVOS = data['eventDayVOS'] as List<dynamic>?;
        if (eventDayVOS != null && eventDayVOS.isNotEmpty) {
          final groupedEvents = <String, List<EventItem>>{};

          for (final dayData in eventDayVOS) {
            final recordDate = dayData['recordDate'] as String? ?? '';
            final weekName = dayData['weekName'] as String? ?? '';
            final dateKey = '$recordDate，$weekName';

            final eventVOS = dayData['eventVOS'] as List<dynamic>?;
            if (eventVOS != null && eventVOS.isNotEmpty) {
              final events = <EventItem>[];

              for (final eventData in eventVOS) {
                final eventInfo = eventData['eventInfo'] as String? ?? '';
                final recordScores =
                    eventData['recordScores'] as String? ?? '0';
                final recordTime = eventData['recordTime'] as String? ?? '';

                // 跳过空内容的事件
                if (eventInfo.isEmpty) {
                  continue;
                }

                final score = int.tryParse(recordScores) ?? 0;
                final isPositive = score >= 0; // 0分也算正分

                events.add(EventItem(
                  content: eventInfo,
                  score: score.abs(),
                  isPositive: isPositive,
                  time: recordTime,
                ));
              }

              if (events.isNotEmpty) {
                groupedEvents[dateKey] = events;
              }
            }
          }

          state.groupedEvents.value = groupedEvents;
        } else {
          state.groupedEvents.value = {};
        }
      } else {
        state.groupedEvents.value = {};
        _updateDateRangeText();
      }
    } catch (e) {
      print('❌ 加载事件数据失败: $e');
      state.groupedEvents.value = {};
      _updateDateRangeText();
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 切换时间段（日/周/月）
  void changePeriod(int index) {
    state.selectedPeriod.value = index;
    _updateDateRangeText();
    _loadEvents();
  }

  /// 更新日期范围文本
  void _updateDateRangeText() {
    final now = DateTime.now();
    switch (state.selectedPeriod.value) {
      case 0: // 日
        state.dateRangeText.value =
            '${now.year}年${now.month.toString().padLeft(2, '0')}月${now.day.toString().padLeft(2, '0')}日，星期${_getWeekday(now.weekday)}';
        break;
      case 1: // 周
        final weekStart = now.subtract(Duration(days: now.weekday - 1));
        final weekEnd = weekStart.add(const Duration(days: 6));
        state.dateRangeText.value =
            '${weekStart.year}年${weekStart.month.toString().padLeft(2, '0')}月${weekStart.day.toString().padLeft(2, '0')}日，星期${_getWeekday(weekStart.weekday)}—${weekEnd.year}年${weekEnd.month.toString().padLeft(2, '0')}月${weekEnd.day.toString().padLeft(2, '0')}日，星期${_getWeekday(weekEnd.weekday)}';
        break;
      case 2: // 月
        final monthStart = DateTime(now.year, now.month, 1);
        final monthEnd = DateTime(now.year, now.month + 1, 0);
        state.dateRangeText.value =
            '${monthStart.year}年${monthStart.month.toString().padLeft(2, '0')}月${monthStart.day.toString().padLeft(2, '0')}日，星期${_getWeekday(monthStart.weekday)}—${monthEnd.year}年${monthEnd.month.toString().padLeft(2, '0')}月${monthEnd.day.toString().padLeft(2, '0')}日，星期${_getWeekday(monthEnd.weekday)}';
        break;
    }
  }

  /// 获取星期几
  String _getWeekday(int weekday) {
    const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
    return weekdays[weekday - 1];
  }

  /// 根据指定日期加载数据
  void loadDataByDate(String recordDate) {
    print('📅 根据日期加载事件小计数据: $recordDate');
    
    // 解析日期字符串
    try {
      final parts = recordDate.split('-');
      if (parts.length == 3) {
        final year = int.parse(parts[0]);
        final month = int.parse(parts[1]);
        final day = int.parse(parts[2]);
        final selectedDate = DateTime(year, month, day);
        
        // 更新日期范围文本
        state.dateRangeText.value =
            '$year年${month.toString().padLeft(2, '0')}月${day.toString().padLeft(2, '0')}日，星期${_getWeekday(selectedDate.weekday)}';
      }
    } catch (e) {
      print('⚠️ 解析日期失败: $e');
    }

    // 重新加载数据
    _loadEvents();
  }
}
